package cn.wh.org.service.impl;

import cn.wh.basic.service.impl.BaseServiceImpl;
import cn.wh.basic.util.MD5Utils;
import cn.wh.basic.util.PageList;
import cn.wh.basic.util.StrUtils;
import cn.wh.org.domain.Employee;
import cn.wh.org.mapper.EmployeeMapper;
import cn.wh.org.query.EmployeeQuery;
import cn.wh.org.service.IEmployeeService;
import cn.wh.user.domain.Logininfo;
import cn.wh.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void save(Employee employee) {
        initEmployee(employee);
        //要级联保存logininfo
        Logininfo logininfo = emp2Logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }
    private Logininfo emp2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);//注意：一定要手动设置，这是员工
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

    @Override
    public void update(Employee employee) {
        employeeMapper.update(employee);
        Logininfo logininfo = logininfoMapper.loadById(employee.getLogininfo_id());
        BeanUtils.copyProperties(employee,logininfo);
        logininfoMapper.update(logininfo);
    }

    @Override
    public void removeById(Long id) {
        Employee employee = employeeMapper.loadById(id);
        employeeMapper.deleteById(id);
        logininfoMapper.deleteById(employee.getLogininfo_id());
    }

    @Override
    public Employee loadByLogininfoId(Long id) {
        Employee employee = employeeMapper.loadByLogininfoId(id);
        return employee;
    }

    @Override
    public List<Employee> queryEmp(Long shopId) {

        return employeeMapper.loadByEmp(shopId);
    }

}
